package com.cowain.monitor.utils;

import com.alibaba.fastjson.JSONArray;
import com.cowain.monitor.dao.PmsEhrContentLogDao;
import com.cowain.monitor.dao.PmsErpContentLogDao;
import com.cowain.monitor.dao.PmsErpErrorLogDao;
import com.cowain.monitor.datasources.DataSourceNames;
import com.cowain.monitor.datasources.annotation.DataSource;
import com.cowain.monitor.entity.*;
import com.cowain.monitor.service.PmsErpContentLogService;
import lombok.Data;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 *  
 *  * @author 冬暖
 *  * @projectName pms-monitor
 *  * @title     PmsProjectUtil   
 *  * @package    com.cowain.monitor.utils  
 *  * @description    项目配置       
 *  * @date   2020/7/27 19:06  
 *  * @version V1.0.0
 *  
 */
@Component
@ConfigurationProperties(prefix = "project")
@Data
public class PmsProjectUtil {
//    @Value("${project.first}")
    public  Integer first;
//    @Value("${project.end}")
    public  Integer end;
//    @Value("${project.num}")
    public  Integer num;
    public  String userUrl;
    public  String deptUrl;
    @Autowired
    private PmsErpContentLogDao contentLogDao;
    @Autowired
    private PmsErpErrorLogDao erpErrorLogDao;
    @Autowired
    private PmsEhrContentLogDao ehrContentLogDao;

    /**
     * 添加集合内容
     */
    public List<Long> addList(List<PmsOrderInfoEntity> infoList,List<PmsOrderInfoEntity> list1){
        //拿到所有数据的id
        List<Long> longList = infoList.stream().map(PmsOrderInfoEntity::getProjectId).collect(Collectors.toList());

        //添加报错日志
        addErrorLog(longList,infoList);
        if (longList.size() > 0){

            //去除重复数据
            LinkedHashSet<Long> set = new LinkedHashSet<>(longList);

            //拿到重复示数据
            Collection disjunction = CollectionUtils.disjunction(longList, set);
            List<Long> ids = new ArrayList<>(disjunction);
            if(ids != null && ids.size() > 0){

                //拿到重复数据放入修改集合中，不重复数据放入新增集合中
                ids.forEach(id -> {
                    PmsOrderInfoEntity infoEntity = infoList.stream().filter(item -> item.getProjectId() != null && item.getProjectId().equals(id)).findFirst().get();
                    infoList.remove(infoEntity);
                    list1.add(infoEntity);
                });
            }
        }
        return longList;
    }

    /**
     * 添加集合内容
     */
    public List<Long> addClientList(List<PmsClientEntity> infoList, List<PmsClientEntity> list1){
        List<Long> longList = infoList.stream().map(PmsClientEntity::getId).collect(Collectors.toList());
        addErrorLogs(longList,infoList);
        if(longList.size() > 0){
            LinkedHashSet<Long> set = new LinkedHashSet<>(longList);
            Collection disjunction = CollectionUtils.disjunction(longList, set);
            List<Long> ids = new ArrayList<>(disjunction);
            if(ids != null && ids.size() > 0){
                ids.forEach(id -> {
                    PmsClientEntity infoEntity = infoList.stream().filter(item -> item.getId().equals(id)).findFirst().get();
                    infoList.remove(infoEntity);
                    list1.add(infoEntity);
                });
            }
        }
        return longList;
    }

    /**
     * 添加报错日志
     */
    @DataSource(name = DataSourceNames.FIRST)
    public void addErrorLog(List<Long> longList,List<PmsOrderInfoEntity> infoList){
        removeNull(longList);
        if(longList.size() == 0 || longList.size() != infoList.size()){
            StringBuilder builder = new StringBuilder();
            infoList.forEach(info -> {
                if(info.getProjectId() == null){
                    builder.append(info.getProjectNo()).append(",");
                }
            });
            PmsErpErrorLogEntity contentLogEntity = new PmsErpErrorLogEntity();
            contentLogEntity.setInsertTime(new Date());
            contentLogEntity.setInsertUser(PmsConstantUtils.ERP_USER);
            contentLogEntity.setItem("当前项目编号不存在：项目编号为"+ builder.toString());
            contentLogEntity.setNum(Long.valueOf(infoList.size() == 0 ? 0 :infoList.size() - longList.size()));
            erpErrorLogDao.insert(contentLogEntity);
        }
    }

    /**
     * 添加报错日志
     */
    @DataSource(name = DataSourceNames.FIRST)
    public void addErrorLogs(List<?> longList,List<PmsClientEntity> infoList){
        removeNull(longList);
        if(longList.size() == 0 || longList.size() != infoList.size()){
            PmsErpErrorLogEntity contentLogEntity = new PmsErpErrorLogEntity();
            contentLogEntity.setInsertTime(new Date());
            contentLogEntity.setInsertUser(PmsConstantUtils.ERP_USER);
            StringBuilder builder = new StringBuilder();
            infoList.forEach(info -> {
                if(info.getId() == null){
                    builder.append(info).append(",");
                }
            });
            contentLogEntity.setItem("当前编号不存在，为"+ builder.toString());
            if(infoList.size() >0){
                contentLogEntity.setNum(Long.valueOf(infoList.size() - longList.size()));
            }else {
                contentLogEntity.setNum(0L);
            }
            erpErrorLogDao.insert(contentLogEntity);
        }
    }
    /**
     * 添加报错日志
     */
    @DataSource(name = DataSourceNames.FIRST)
    public void addSupplierErrorLogs(List<?> longList,List<PmsSupplierEntity> infoList){
        removeNull(longList);
        if(longList.size() == 0 || longList.size() != infoList.size()){
            PmsErpErrorLogEntity contentLogEntity = new PmsErpErrorLogEntity();
            contentLogEntity.setInsertTime(new Date());
            contentLogEntity.setInsertUser(PmsConstantUtils.ERP_USER);
            StringBuilder builder = new StringBuilder();
            infoList.forEach(info -> {
                if(info.getSupplierCode() == null && StringUtils.isBlank(info.getSupplierCode())){
                    builder.append(info).append(",");
                }
            });
            contentLogEntity.setItem("当前编号不存在，为"+ builder.toString());
            if(infoList.size() >0){
                contentLogEntity.setNum(Long.valueOf(infoList.size() - longList.size()));
            }else {
                contentLogEntity.setNum(0L);
            }
            erpErrorLogDao.insert(contentLogEntity);
        }
    }
    /**
     * 添加报错日志
     */
    @DataSource(name = DataSourceNames.FIRST)
    public void addUserErrorLogs(List<?> longList,List<PmsSysUserEntity> infoList){
        removeNull(longList);
        if(longList.size() == 0 || longList.size() != infoList.size()){
            PmsErpErrorLogEntity contentLogEntity = new PmsErpErrorLogEntity();
            contentLogEntity.setInsertTime(new Date());
            contentLogEntity.setInsertUser(PmsConstantUtils.EHR_USER);
            StringBuilder builder = new StringBuilder();
            infoList.forEach(info -> {
                if(info.getUsername() == null && StringUtils.isBlank(info.getUsername())){
                    builder.append(info).append(",");
                }
            });
            contentLogEntity.setItem("当前用户名不存在，为"+ builder.toString());
            if(infoList.size() >0){
                contentLogEntity.setNum(Long.valueOf(infoList.size() - longList.size()));
            }else {
                contentLogEntity.setNum(0L);
            }
            erpErrorLogDao.insert(contentLogEntity);
        }
    }
    @DataSource(name = DataSourceNames.FIRST)
    public void addDeptErrorLogs(List<?> longList,List<PmsSysDeptEntity> infoList){
        removeNull(longList);
        if(longList.size() == 0 || longList.size() != infoList.size()){
            PmsErpErrorLogEntity contentLogEntity = new PmsErpErrorLogEntity();
            contentLogEntity.setInsertTime(new Date());
            contentLogEntity.setInsertUser(PmsConstantUtils.EHR_DEPT);
            StringBuilder builder = new StringBuilder();
            infoList.forEach(info -> {
                if(info.getDeptId() == null){
                    builder.append(info).append(",");
                }
            });
            contentLogEntity.setItem("当前部门的id不存在，为"+ builder.toString());
            if(infoList.size() >0){
                contentLogEntity.setNum(Long.valueOf(infoList.size() - longList.size()));
            }else {
                contentLogEntity.setNum(0L);
            }
            erpErrorLogDao.insert(contentLogEntity);
        }
    }
    /**
     * 添加内容
     * @param lists 添加的内容
     */
    @DataSource(name = DataSourceNames.FIRST)
    public void addLog(List<?> lists,List<?> updateList,String insertUser,String updateUser){
        List<PmsErpContentLogEntity> contentLogEntityList = new ArrayList<>();
        if(lists != null && lists.size() > 0){
            PmsErpContentLogEntity erpContentLogEntity = new PmsErpContentLogEntity();
            erpContentLogEntity.setInsertTime(new Date());
            erpContentLogEntity.setInsertUser(insertUser);
            erpContentLogEntity.setInsertItem(lists.toString());
            erpContentLogEntity.setInsertNum(Long.valueOf(lists.size()));
            contentLogEntityList.add(erpContentLogEntity);
        }
        if(updateList != null && updateList.size() > 0){
            PmsErpContentLogEntity erpContentLogEntity = new PmsErpContentLogEntity();
            erpContentLogEntity.setUpdateTime(new Date());
            erpContentLogEntity.setUpdateUser(updateUser);
            erpContentLogEntity.setUpdateItem(updateList.toString());
            erpContentLogEntity.setUpdateNum(Long.valueOf(updateList.size()));
            contentLogEntityList.add(erpContentLogEntity);
        }
        if(contentLogEntityList.size() > 0){
            contentLogDao.insertList(contentLogEntityList);
        }
    }

    /**
     * 添加集合内容
     */
    public List<Long> addSupperList(List<PmsSupplierEntity> infoList, List<PmsSupplierEntity> list1) {
        List<Long> longList = infoList.stream().map(PmsSupplierEntity::getId).collect(Collectors.toList());
        addSupplierErrorLogs(longList,infoList);
        if(longList.size() > 0){
            LinkedHashSet<Long> set = new LinkedHashSet<>(longList);
            Collection disjunction = CollectionUtils.disjunction(longList, set);
            List<Long> ids = new ArrayList<>(disjunction);
            if(ids != null && ids.size() > 0){
                ids.forEach(id -> {
                    PmsSupplierEntity infoEntity = infoList.stream().filter(item -> item.getId().equals(id)).findFirst().get();
                    infoList.remove(infoEntity);
                    list1.add(infoEntity);
                });
            }
        }
        return longList;
    }

    /**
     *  去除集合中为null的元素
     */
    public static <T> List<T> removeNull(List<? extends T> oldList) {
        oldList.removeAll(Collections.singleton(null));
        return (List<T>) oldList;
    }

    /**
     *  拆分集合
     *  @param <T>
     *  @param resList 要拆分的集合
     *  @param count 每个集合的元素个数
     *  @return 返回拆分后的各个集合
     **/
    public  <T> List<List<T>> split(List<T> resList, int count) {
        if (resList == null || count < 1){
            return null;
        }
        List<List<T>> ret = new ArrayList<List<T>>();
        int size = resList.size();
        if (size <= count) {
            // 数据量不足count指定的大小
            ret.add(resList);
        } else {
            int pre = size / count;
            int last = size % count;
            // 前面pre个集合，每个大小都是count个元素
            for (int i = 0; i < pre; i++) {
                List<T> itemList = new ArrayList<T>();
                for (int j = 0; j < count; j++) {
                    itemList.add(resList.get(i * count + j));
                }
                ret.add(itemList);
            }
            // last的进行处理
            if (last > 0) {
                List<T> itemList = new ArrayList<T>();
                for (int i = 0; i < last; i++) {
                    itemList.add(resList.get(pre * count + i));
                }
                ret.add(itemList);
            }
        }
        return ret;
    }

    /**
     * 寻找code码
     * @param name 状态
     * @return code码
     */
    public Long findCode(String type,String name){
        Long code = null;
        if(type.equals(PmsConstantUtils.STATUS_SO)){
            switch (name){
                case "草稿":
                    code = 14040L;
                    break;
                case "开立":
                    code = 14041L;
                    break;
                case "核准中":
                    code = 14042L;
                    break;
                case "自然关闭":
                    code = 14043L;
                    break;
                case "短缺关闭":
                    code = 14044L;
                    break;
                case "超额关闭":
                    code = 14045L;
                    break;
                default:
                    break;
            }
        }else if(type.equals(PmsConstantUtils.STATUS_SOF)){
            switch (name){
                case "开立":
                    code = 14050L;
                    break;
                case "核准中":
                    code = 14051L;
                    break;
                case "核准":
                    code = 14052L;
                    break;
                case "关闭":
                    code = 14053L;
                    break;
                default:
                    break;
            }
        }else {
            switch (name){
                case "开立":
                    code = 14060L;
                    break;
                case "核准中":
                    code = 14061L;
                    break;
                case "已核准":
                    code = 14062L;
                    break;
                default:
                    break;
            }
        }
        return code;
    }

    /**
     * 获取性别
     * @param sex 字符串
     * @return 性别
     */
    public Integer findSex(String sex){
        Integer gender = null;
        switch (sex){
            case "男":
                gender = 2;
                break;
            case "女":
                gender = 1;
            default:
                gender = 3;
                break;
        }
        return gender;
    }

    /**
     * 添加内容
     * @param lists 添加的内容
     * @param date 时间
     */
    @DataSource(name = DataSourceNames.FIRST)
    public void addEhrLog(List<?> lists, List<?> updateList, String insertUser, String updateUser, Date date){
        List<PmsEhrContentLogEntity> contentLogEntityList = new ArrayList<>();
        if(lists != null && lists.size() > 0){
            PmsEhrContentLogEntity ehrContentLogEntity = new PmsEhrContentLogEntity();
            ehrContentLogEntity.setInsertTime(new Date());
            ehrContentLogEntity.setInsertUser(insertUser);
            ehrContentLogEntity.setInsertItem(lists.toString());
            ehrContentLogEntity.setInsertNum((long) lists.size());
            ehrContentLogEntity.setStartTime(date);
            ehrContentLogEntity.setStartItem(insertUser);
            contentLogEntityList.add(ehrContentLogEntity);
        }
        if(updateList != null && updateList.size() > 0){
            PmsEhrContentLogEntity ehrContentLogEntity = new PmsEhrContentLogEntity();
            ehrContentLogEntity.setUpdateTime(new Date());
            ehrContentLogEntity.setUpdateUser(updateUser);
            ehrContentLogEntity.setUpdateItem(updateList.toString());
            ehrContentLogEntity.setUpdateNum((long) updateList.size());
            ehrContentLogEntity.setStartTime(date);
            ehrContentLogEntity.setStartItem(updateUser);
            contentLogEntityList.add(ehrContentLogEntity);
        }
        if(contentLogEntityList.size() > 0){
            ehrContentLogDao.insertList(contentLogEntityList);
        }
    }

    /**
     * 获取用户集合
     * @param insertUser 用户信息
     * @param list1 集合
     * @return 用户
     */
    public List<String> addUserList(List<PmsSysUserEntity> insertUser, List<PmsSysUserEntity> list1) {
        List<String> longList = insertUser.stream().map(PmsSysUserEntity::getUsername).collect(Collectors.toList());
        addUserErrorLogs(longList,insertUser);
        if(longList.size() > 0){
            LinkedHashSet<String> set = new LinkedHashSet<>(longList);
            Collection disjunction = CollectionUtils.disjunction(longList, set);
            List<String> ids = new ArrayList<>(disjunction);
            if(ids.size() > 0){
                ids.forEach(id -> {
                    PmsSysUserEntity infoEntity = insertUser.stream().filter(item -> item.getUsername().equals(id)).findFirst().get();
                    insertUser.remove(infoEntity);
                    list1.add(infoEntity);
                });
            }
        }
        return longList;
    }

    /**
     * 修改时间
     */
    public String updateTime(String url,Date start) {
        Map<String, String> map =new HashMap<>();
        String startTime = null;
        SimpleDateFormat fat = new SimpleDateFormat("yyyy-MM-dd");
        if(start != null){
            startTime = fat.format(start);
        }else {
            startTime = "2010-01-01 01:00:00";
//            startTime = "2010-01-01";
        }
//        String endTime = "2024-08-08";
        map.put("startTime",startTime);
//        map.put("endTime",endTime);
        return HttpClientUtil.doGet(url, map);
    }

    /**
     * 获取公司字典值
     * @param category 类别
     * @return code
     */
    public Integer findCompany(String category) {
        Long code = null;
        switch (category){
            case "公司":
                code = PmsConstantUtils.IS_ORG_TRUE;
                break;
            case "部门":
                code = PmsConstantUtils.IS_ORG_FALSE;
                break;
            default:
                break;
        }
        return code == null ? null : code.intValue();
    }

    /**
     * 保存部门组织信息
     * @param insertDept 部门
     * @param list1 集合
     * @return 部门信息
     */
    public List<Long> addDeptList(List<PmsSysDeptEntity> insertDept, List<PmsSysDeptEntity> list1) {
        List<Long> longList = insertDept.stream().map(PmsSysDeptEntity::getDeptId).collect(Collectors.toList());
        addDeptErrorLogs(longList,insertDept);
        if(longList.size() > 0){
            LinkedHashSet<Long> set = new LinkedHashSet<>(longList);
            Collection disjunction = CollectionUtils.disjunction(longList, set);
            List<Long> ids = new ArrayList<>(disjunction);
            if(ids.size() > 0){
                ids.forEach(id -> {
                    PmsSysDeptEntity infoEntity = insertDept.stream().filter(item -> item.getDeptId().equals(id)).findFirst().get();
                    insertDept.remove(infoEntity);
                    list1.add(infoEntity);
                });
            }
        }
        return longList;
    }

    /**
     * 保存负责人信息
     * @param insertDept 部门
     * @param list1 集合
     * @return 部门信息
     */
    public List<Long> addPersonList(List<PmsDeptPersonEntity> insertDept, List<PmsDeptPersonEntity> list1) {
        List<Long> longList = insertDept.stream().map(PmsDeptPersonEntity::getDeptId).collect(Collectors.toList());
        addPersonErrorLogs(longList,insertDept);
        if(longList.size() > 0){
            LinkedHashSet<Long> set = new LinkedHashSet<>(longList);
            Collection disjunction = CollectionUtils.disjunction(longList, set);
            List<Long> ids = new ArrayList<>(disjunction);
            if(ids.size() > 0){
                ids.forEach(id -> {
                    PmsDeptPersonEntity infoEntity = insertDept.stream().filter(item -> item.getDeptId().equals(id)).findFirst().get();
                    insertDept.remove(infoEntity);
                    list1.add(infoEntity);
                });
            }
        }
        return longList;
    }

    private void addPersonErrorLogs(List<Long> longList, List<PmsDeptPersonEntity> insertDept) {
        removeNull(longList);
        if(longList.size() == 0 || longList.size() != insertDept.size()){
            PmsErpErrorLogEntity contentLogEntity = new PmsErpErrorLogEntity();
            contentLogEntity.setInsertTime(new Date());
            contentLogEntity.setInsertUser(PmsConstantUtils.EHR_DEPT);
            StringBuilder builder = new StringBuilder();
            insertDept.forEach(info -> {
                if(info.getDeptId() == null){
                    builder.append(info).append(",");
                }
            });
            contentLogEntity.setItem("当前部门的id不存在，为"+ builder.toString());
            if(insertDept.size() >0){
                contentLogEntity.setNum(Long.valueOf(insertDept.size() - longList.size()));
            }else {
                contentLogEntity.setNum(0L);
            }
            erpErrorLogDao.insert(contentLogEntity);
        }
    }
}
